package com.example.nonggo.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.example.nonggo.contract.OnLocationCallback;

import java.util.List;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.tasks.Task;

public class LocationOnUtils {



    /**
     * 获取最后一次已知位置（快速但不一定准确）
     * 优先尝试 GPS，其次是网络定位
     */
    public static void getLastKnownLocation(
            @NonNull Context context,
            @NonNull OnLocationCallback callback
    ) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        // 1. 检查权限
        if (!checkPermissions(context)) {
            callback.onLocationError("缺少定位权限");
            return;
        }

        // 2. 检查定位服务状态
        if (!isLocationEnabled(context)) {
            callback.onLocationError("请先开启定位服务");
            return;
        }

        // 3. 尝试获取网络定位
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null) {
                callback.onLocationReceived(location.getLatitude(), location.getLongitude());
                return;
            }
        }

        // 4. 如果网络定位失败，检查GPS状态并尝试GPS定位
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location != null) {
                    callback.onLocationReceived(location.getLatitude(), location.getLongitude());
                    return;
                }
            }
        } else {
            callback.onLocationError("GPS定位服务未启用");
            return;
        }

        // 5. 如果都失败，请求一次实时位置
        requestSingleLocation(context, callback);
    }

    private static void requestSingleLocation(
            @NonNull Context context,
            @NonNull OnLocationCallback callback
    ) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        
        LocationListener listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                callback.onLocationReceived(location.getLatitude(), location.getLongitude());
                locationManager.removeUpdates(this);
            }

            @Override
            public void onProviderDisabled(String provider) {
                callback.onLocationError("定位提供者被禁用: " + provider);
                locationManager.removeUpdates(this);
            }

            @Override
            public void onProviderEnabled(String provider) {
                callback.onLocationError("onProviderEnabled: " + provider);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {}
        };

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            // 先尝试网络定位
            if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, listener, Looper.getMainLooper());
            }
            // 如果网络定位不可用，尝试GPS定位
            else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, listener, Looper.getMainLooper());
            }
            else {
                callback.onLocationError("无可用定位服务");
            }
        }
    }

    /**
     * 请求实时位置更新（需要主动停止）
     * @param provider 定位提供者：LocationManager.GPS_PROVIDER 或 LocationManager.NETWORK_PROVIDER
     */
    public static void requestLocationUpdates(
            @NonNull Context context,
            @NonNull String provider,
            long minTimeMs, // 最小更新时间间隔（毫秒）
            float minDistanceM, // 最小位置变化距离（米）
            @NonNull OnLocationCallback callback
    ) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        // 1. 检查权限
        if (!checkPermissions(context)) {
            callback.onLocationError("缺少定位权限");
            return;
        }

        // 2. 检查提供者是否可用
        if (!locationManager.isProviderEnabled(provider)) {
            callback.onLocationError("定位提供者未启用: " + provider);
            return;
        }

        // 3. 注册位置监听器
        LocationListener listener = new LocationListener() {
            @Override
            public void onLocationChanged(@NonNull Location location) {
                callback.onLocationReceived(location.getLatitude(), location.getLongitude());
            }

            @Override
            public void onProviderDisabled(@NonNull String provider) {
                callback.onLocationError("定位提供者被禁用: " + provider);
            }

            @Override
            public void onProviderEnabled(@NonNull String provider) {
                callback.onLocationError("onProviderEnabled: " + provider);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                callback.onLocationError("onStatusChanged: " + status);
            }
        };

        // 4. 开始监听
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            locationManager.requestLocationUpdates(
                    provider,
                    minTimeMs,
                    minDistanceM,
                    listener,
                    Looper.getMainLooper()
            );
        }
    }

    /**
     * 停止实时位置更新
     */
    public static void stopLocationUpdates(
            @NonNull Context context,
            @NonNull LocationListener listener
    ) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        locationManager.removeUpdates(listener);
    }

    // 检查定位权限
    public static boolean checkPermissions(Context context) {
        return ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }

    // 新增方法：检查定位服务是否开启
    public static boolean isLocationEnabled(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    }
}